<template>
  <div>
    <ContentWrap>
      <el-form ref="queryFormRef" :model="form" :inline="true" class="demo-form-inline mb-4">
        <el-form-item label="关联用户" prop="userId">
          <el-select
            v-model="form.userId"
            filterable
            remote
            reserve-keyword
            placeholder="请选择"
            :remote-method="remoteMethod"
            :loading="loading"
            class="!w-200px"
          >
            <el-option
              v-for="item in userOptions"
              :key="item.id"
              :label="item.nickname"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="primary" @click="handleView('add')">新增批次</el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>
    <ContentWrap>
      <el-table :data="tableData" :loading="loading" stripe :show-overflow-tooltip="true">
        <el-table-column label="批次" prop="id" align="center" />
        <el-table-column label="批次名称" prop="batchName" align="center" />
        <el-table-column label="张数(总量)" prop="amount" align="center" />
        <el-table-column label="关联用户ID" prop="userId" align="center" />
        <el-table-column label="生成时间" prop="createTime" align="center">
          <template #default="scope">
            <span>{{
              scope.row.createTime ? formatDate(scope.row.createTime, 'YYYY-MM-DD HH:mm:ss') : '--'
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="有效期" prop="expiredTime" align="center">
          <template #default="scope">
            <span>{{
              scope.row.effectTime
                ? formatDate(scope.row.effectTime, 'YYYY-MM-DD HH:mm:ss')
                : '--'
            }}</span>
            <span> - </span>
            <span>{{
              scope.row.expiredTime
                ? formatDate(scope.row.expiredTime, 'YYYY-MM-DD HH:mm:ss')
                : '--'
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="已使用" prop="usedAmount" align="center" />
        <el-table-column label="剩余" prop="remainAmount" align="center" />
        <el-table-column label="操作" prop="action" align="center">
          <template #default="scope">
            <el-button type="primary" link @click="seeRecordRef.open(scope.row)">明细</el-button>
            <el-popconfirm title="是否确认导出卡号?" @confirm="exportCard(scope.row)" @click.stop>
              <template #reference>
                <el-button type="primary" link>导出</el-button>
              </template>
            </el-popconfirm>
            <el-popconfirm title="是否确认删除?" @confirm="delCard(scope.row)" @click.stop>
              <template #reference>
                <el-button type="danger" link>删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        :total="total"
        v-model:page="form.pageNo"
        v-model:limit="form.pageSize"
        @pagination="getList"
      />
    </ContentWrap>
    <AddBatch ref="addBatchRef" @success="getList" />
    <SeeRecord ref="seeRecordRef" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getPosterReferralRelationPage, getPosterTypeList } from '@/api/allApplication/poster/index'
import { formatDate } from '@/utils/formatTime'
import * as UserApi from '@/api/system/user'
import { PhysicalApi } from '@/api/allApplication/physical'
import { getUserPage } from '@/api/member/user'
import AddBatch from './addBatch.vue'
import SeeRecord from './seeRecord.vue'
import download from '@/utils/download'

const addBatchRef = ref()
const seeRecordRef = ref()
const queryFormRef = ref()
const message = useMessage() // 消息弹窗

const form = ref({
  userId: undefined as any,
  pageNo: 1,
  pageSize: 10
})
const userOptions = ref([])
const state = reactive({
  tableData: [],
  total: 0,

  posterTypeList: [] as any[]
})
const { tableData, total, posterTypeList } = toRefs(state)
const loading = ref(false)
const handleSearch = () => {
  form.value.pageNo = 1
  getList()
}
const handleReset = () => {
  queryFormRef.value.resetFields()
  handleSearch()
}
const getList = async () => {
  const res = await PhysicalApi.getPhysicalCardPage({
    ...form.value,
    pageNo: form.value.pageNo,
    pageSize: form.value.pageSize
  })
  state.tableData = res.list || []
  state.total = res.total || 0
}
const remoteMethod = async (query) => {
  if (query) {
    loading.value = true
    const data = await getUserPage({ pageNo: 1, pageSize: 10, mobile: query })
    userOptions.value = data.list
    loading.value = false
  } else {
    userOptions.value = []
  }
}
const handleView = (type: string, row?: any) => {
  addBatchRef.value.open(type, row)
}
const exportCard = async (row: any) => {
    const loading = ElLoading.service({
    lock: true,
    text: '正在导出，请稍候...',
    background: 'rgba(0, 0, 0, 0.7)',
  });

  try {
    const data = await PhysicalApi.exportPhysicalCardDetailsExcel(row.id);
    console.log('data',data)
    download.excel(data, `${row.batchName}.xls`);
  } catch (error) {
    ElMessage.error('导出失败，请重试');
    console.error('导出失败:', error);
  } finally {
    loading.close();
  }
}
const delCard = async (row: any) => {
  const data = await PhysicalApi.delPhysicalCard(row.id)
  if (data) {
    getList()
    ElMessage.success('删除成功')
  }
}
onMounted(async () => {
  await getList()
})
</script>
